 //
//  EmoticonController.swift
//  01-表情键盘(绑定数据)
//
//  Created by gxiangzi on 15/9/13.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

private let EmoticonCellID = "EmoticonCellID"

class EmoticonController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 创建一个属性，来记录闭包
    var selectEmoticonCallBack:(emoticon:Emoticon)->()
    
    
    init(selectEmoticon:(emoticon:Emoticon)->()) {
        
        selectEmoticonCallBack = selectEmoticon
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.loadEmoticon()
        
        setupUI()
        prepareToolBar()
        prepareCollection()
        
    }
    
    // 点击 ToolBar 让collectionView 跳转到相应的组
    @objc private func clickItem(item:UIBarButtonItem) {
        
    let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)        
    }
    
     // MARK: - 布局界面
    private func setupUI() {
        // 1.添加控件
        self.view.addSubview(toolBar)
        self.view.addSubview(collectionView)
        
        // 2.设置约束
        // 1> 设置 ToolBar 的约束
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 44))
        
        // 2> 设置 collectionView 的约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
        let cons = NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0)
        view.addConstraint(cons)
        view.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0))
    }
    
    private func prepareToolBar() {
        toolBar.tintColor = UIColor.grayColor()
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        
        for p in viewModel.packages {
            
            items.append(UIBarButtonItem(title: p.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            
            items.last!.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
    }
    
    private func prepareCollection() {
        
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.darkGrayColor()
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellID)
        
    }
    
    // MARK: - 懒加载控件
    /// 添加 collectionView
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    /// 添加工具栏
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    // 添加数据模型
    private lazy var viewModel:EmoticonViewModel = EmoticonViewModel()

}

// MARK: - 数据源 & 代理
extension EmoticonController {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.packages.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellID, forIndexPath: indexPath) as! EmoticonCell
        
        let package = viewModel.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        cell.emoticon = emoticon
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return viewModel.packages[section].emoticons.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        selectEmoticonCallBack(emoticon: viewModel.emoticon(indexPath))
    }
    
    
    
}

// MARK: - 布局的属性反复
private class EmoticonLayout : UICollectionViewFlowLayout {
    
    private override func prepareLayout() {
        super.prepareLayout()
        
        let w = collectionView!.bounds.width / 7
        // iPhone 5 如果用 0.5 会每页显示两行，因为浮点数的原因，计算会有偏差！
        let margin = (collectionView!.bounds.height - 3 * w) * 0.499
        itemSize = CGSize(width: w, height: w)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
    
}


private class EmoticonCell:UICollectionViewCell {
    
    var emoticon :Emoticon? {
        didSet {
            //  默认的图片或者 浪小花 会使用png,如果没有图片，自动会清空 image
           emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            // emoji 是使用文字转换的即可，如果没有文字，会自动清空 title
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemove {
                    emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                    emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        // 设置字体
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled  = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
     // MARK: - 懒加载数据
    private lazy var emoticonButton:UIButton = UIButton()
    
}


